'use strict';
const axios = require('axios')
const urlJoin = require('url-join')
const semver = require("semver")

function getNpmInfo(npmName, registry) {
    if (!npmName) {
        return null
    }
    const registryUrl = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl, npmName) // 拼接字符串
    return axios.get(npmInfoUrl).then(response => {
        if (response.status == 200) {
            return response.data
        } else {
            return null
        }
    }).catch(err => {
        return Promise.reject(err)
    })
}
function getDefaultRegistry(isOriginal = false) {
    return isOriginal ? "https://registry.npmjs.org" : "https://registry.npmmirror.com"
}
// 获取所有 的versions
async function getNpmVersions(npmName,registry) {
    const data = await getNpmInfo(npmName,registry)
    if(data) {
      return  Object.keys(data.versions)
    }else {
        return []
    }
}
// 获取所有满足条件的版本号
function getSemverVersions(baseVersion,versions) {
   return versions
   .filter(version => semver.satisfies(version,`^${baseVersion}`))
    .sort((a, b) => {
        return semver.gt(a, b)
    })
}
// 进行对比获取当前最大的版本号
async function getNpmSemverVersion(baseVersion,npmName,registry) {
    const versions = await getNpmVersions(npmName,registry)
    const newVersions = getSemverVersions(baseVersion,versions)
    if(newVersions && newVersions.length > 0) {
        return newVersions.reverse()[0]
    }else{
        return null
    }
   
}
module.exports = {getNpmInfo,getNpmVersions,getNpmSemverVersion};